package personal.emailsender.server.service.impl;

import java.util.logging.Logger;

import javax.ws.rs.core.MediaType;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.util.MultivaluedMapImpl;

import personal.emailsender.server.service.EmailSendService;
import personal.emailsender.shared.data.EmailContent;
import personal.emailsender.shared.enums.EmailServer;

public class MailGunSendingServiceImpl implements EmailSendService {

	private static final Logger logger =
			Logger.getLogger(MailGunSendingServiceImpl.class.getSimpleName());

	@Override
	public boolean sendEmail(EmailContent emailContent) {
		Client client = Client.create();
		WebResource webResource = client.resource(EmailServer.MAILGUN
				.getServerUrl());
		MultivaluedMapImpl formData = new MultivaluedMapImpl();
		// TODO: update from once domain is verified
		formData.add("from", "Mailgun Sandbox <postmaster"
				+ "@sandboxe30643abfabb4f4ab8d3e8d4d9ee7d62.mailgun.org>");
		for (String receiverEmail : emailContent.getReceiverEmails()) {
			formData.add("to", receiverEmail);
		}
		formData.add("subject", emailContent.getSubject());
		formData.add("html", emailContent.getContent());
		logger.info("Form data before sending to MailGun: " + formData);
		return 200 == webResource.type(MediaType.APPLICATION_FORM_URLENCODED)
				.post(ClientResponse.class, formData).getStatus();
	}
}
